from rest_framework.pagination import PageNumberPagination
from rest_framework.viewsets import ModelViewSet
from rest_framework.views import *
from rest_framework.response import Response

class CustomViewSet(ModelViewSet):
    """重写create、list、update、retrieve、destroy方法，修改响应信息"""

    def create(self, request, *args, **kwargs):
        """创建"""
        response = super(CustomViewSet, self).create(request, *args, **kwargs)
        return Response({'code': 200, 'msg': '创建成功', 'data': [response.data]})

    def retrieve(self, request, *args, **kwargs):
        """查看详情页"""
        response = super(CustomViewSet, self).retrieve(request, *args, **kwargs)
        return Response({'code': 200, 'msg': '查看详情成功', 'data': [response.data]})

    def update(self, request, *args, **kwargs):
        """更新成功"""
        response = super(CustomViewSet, self).update(request, *args, **kwargs)
        return Response({'code': 200, 'msg': '更新成功', 'data': [response.data]})

    def destroy(self, request, *args, **kwargs):
        """删除成功"""
        response = super(CustomViewSet, self).destroy(request, *args, **kwargs)
        return Response({'code': 200, 'msg': '删除成功', 'data': []})

    def list(self, request, *args, **kwargs):
        """查看成功"""
        response = super(CustomViewSet, self).list(request, *args, **kwargs)
        return Response({'code': 200, 'msg': '查看成功', 'data': [response.data]})


class CustomPageViewSet(CustomViewSet):
    """分页查看所有信息的重写"""

    def list(self, request, *args, **kwargs):
        """查看成功"""
        response = super(CustomViewSet, self).list(request, *args, **kwargs)
        data = dict(response.data)
        results = data.pop('results')
        data['code'] = 200
        data['msg'] = '查看成功'
        data['data'] = results
        return Response(data)


def exception_handler(exc, context):
    """
    Returns the response that should be used for any given exception.

    By default we handle the REST framework `APIException`, and also
    Django's built-in `Http404` and `PermissionDenied` exceptions.

    Any unhandled exceptions may return `None`, which will cause a 500 error
    to be raised.
    """
    if isinstance(exc, Http404):
        exc = exceptions.NotFound()
        return Response({'code': 404, 'msg': 'Not Found',
                             'data': [], 'errors': [exc.detail]})
    elif isinstance(exc, PermissionDenied):
        exc = exceptions.PermissionDenied()
        return Response({'code': 400, 'msg': 'Permission Denied',
                             'data': [], 'errors': [exc.detail]})

    if isinstance(exc, exceptions.APIException):
        if isinstance(exc.detail, (list)):
            errors = exc.detail
        else:
            errors = [exc.detail]

        set_rollback()
        return Response({'code': 500, 'msg': '出现异常', 'data': [], 'errors': errors})
    return None


class StandardPagination(PageNumberPagination):
    page_size = 100
    page_size_query_param = 'page_size'
